package util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitUtil {


  private static ConnectionFactory connectionFactory;
  static {
    connectionFactory = new ConnectionFactory();//设置连接rabbitmq主机
    connectionFactory.setHost ( "106.55.243.100" );//设置端口号
    connectionFactory.setPort (5672);//设置连接那个虚拟主机
    connectionFactory.setVirtualHost ( "/ems" );//设置访问虚拟主机的用户名和密码
    connectionFactory.setUsername ( "ems" );
    connectionFactory.setPassword ( "123");//获取连接对象
  }

  //建立连接
  public static Connection getConnection(){
    try {
      Connection connection = connectionFactory.newConnection();
      return connection;
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    }
    return null;
  }

  //关闭通道和关闭连接工具方法
  public static void closeConnectionAndChannel(Channel channel, Connection conn ) {

    try {
      if (channel !=null)channel.close();
      if (conn != null)conn.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


}
